const svc = require('../util/service'),
addWord = require('../util/addWord'),
log = require('../util/log'),
urlDao = require('../dao/urlDao'),
uwDao = require('../dao/urlWordDao'),
wordDao = require('../dao/wordDao');

module.exports = (req, res) => {
	svc.handlePost(req, res, (reqObj, fn) => {
		if (!reqObj.oldUrl) {
			fn({
				result: -1,
				msg: '缺少oldUrl'
			})
			return
		}
		if (!reqObj.url) {
			fn({
				result: -1,
				msg: '缺少url'
			})
			return
		}
		if (isNaN(parseFloat(reqObj.p))) {
			fn({
				result: -1,
				msg: 'P不为数值'
			})
			return
		}
		if (require('../../lib/getClass')(reqObj.wordList) != 'Array') {
			fn({
				result: -1,
				msg: 'wordList不为Array'
			})
			return
		}
		var p1 = new Promise((resolve, reject) => {
				urlDao.select({
					url: reqObj.oldUrl
				}, urls => {
					if (urls.length == 0) {
						reject('找不到url')
						return
					}
					var url = urls[0];
					url.url = reqObj.url;
					url.title = reqObj.title;
					url.p = reqObj.p;
					url.lastVisitedTime = new Date();
					urlDao.update(url, () => {
						resolve(url.id)
					})
				})
			}),
		p2 = new Promise(resolve => {
				var promiseList = []
				reqObj.wordList.forEach(reqWord => {
					var sWord = reqWord.word.replace(
							/[^\u4e00-\u9fa5\w\d]/gi, '').toLowerCase();
					if (sWord == '')
						return;
					promiseList.push(new Promise(resolve => {
							new Promise(_resolve => {
								wordDao.findByWord(sWord, word => {
									if (word != null)
										_resolve(word);
									else
										addWord(sWord, _resolve)
								})
							}).then(word => {
								resolve({
									wordId: word.wordId,
									p: reqWord.p
								})
							})
						}))
				})
				Promise.all(promiseList).then(uwList => {
					resolve(uwList)
				})
			});
		Promise.all([p1, p2]).then(result => {
			var urlId = result[0],
			uwList = result[1],
			p1 = new Promise(resolve => {
					updateUwPromiseList = []
					uwList.forEach(uw => {
						uw.urlId = urlId;
						updateUwPromiseList.push(new Promise(resolve => {
								uwDao.findByUrlIdWordId(urlId, uw.wordId, _uw => {
									if (_uw != null) {
										if (_uw.p != uw.p) {
											uwDao.update(uw, () => {
												resolve()
											})
										} else {
											resolve()
										}
									} else {
										uwDao.insert(uw, () => {
											resolve()
										})
									}
								})
							}))
					})
					Promise.all(updateUwPromiseList).then(result => {
						resolve()
					}).catch (err => {
						log(err)
					})
				});
			Promise.all([p1]).then(result => {
				fn({
					result: 1
				}).catch (err => {
					log(err)
				})
			})
		}, result => {
			log(result)
			fn({
				result: -1,
				msg: result.join(',')
			})
		}).catch (err => {
			log(err)
		})
	})
}
